package com.zide.framework.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.zide.common.constant.HttpStatus;
import com.zide.common.exception.ServiceException;
import com.zide.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @author ShiTian
 * @date 2023/3/10 12:16
 */
@Slf4j
@Component
public class AliyunOssUtil {
    private final AliyunOSSConfig aliyunOSSFileConfig;

    public AliyunOssUtil(AliyunOSSConfig aliyunOSSFileConfig) {
        this.aliyunOSSFileConfig = aliyunOSSFileConfig;
    }


    /**
     * 单文件上传
     * @param file
     * @return
     */
    public String uploadSignImage(MultipartFile file,String type) {

        String fileName = getFileName(file);
        String imgName = type + "/" + fileName;
        return updaloadImgFile(file,imgName);
    }


    /**
     * 删除单个文件
     * @param fileName
     */
    public void removeFile(String fileName) {
        fileName = fileName.replaceAll(aliyunOSSFileConfig.getUrlPrefix(),"");
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSFileConfig.getEndpoint(), aliyunOSSFileConfig.getKeyid(), aliyunOSSFileConfig.getKeySecret());
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(aliyunOSSFileConfig.getBucketName(), fileName);
        } catch (OSSException oe) {
            log.error("阿里云OSS删除文件失败===》{}",oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里云OSS删除文件失败===》{}",ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 上传图片
     * @return
     */
    private String updaloadImgFile(MultipartFile file,String imgName) {
        if(StringUtils.isNull(file)) {
            throw new ServiceException("请重新上传！", HttpStatus.NOT_FOUND);
        }
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSFileConfig.getEndpoint(), aliyunOSSFileConfig.getKeyid(), aliyunOSSFileConfig.getKeySecret());
        try {
            // 上传数据
            ossClient.putObject(aliyunOSSFileConfig.getBucketName(), imgName, file.getInputStream());
        } catch (OSSException oe) {
            log.error("上传失败===》{}",oe);
        } catch (ClientException ce) {
            log.error("上传失败===》{}",ce);
        } catch (IOException e) {
            log.error("上传失败===》{}",e);
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return aliyunOSSFileConfig.getUrlPrefix() + imgName;
    }

    private String getFileName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String dateUrl = LocalDate.now().toString().replace("-","/")+"/";
        fileName = dateUrl + uuid + "." + fileName;
        return fileName;
    }
}
